# 建议创建一个新文件: src/execution/planner.py

from types import SimpleNamespace


class QueryPlanner:
    def _clean_op(self, op: str) -> str:
        """清理并转换操作符"""
        # 操作符映射表
        op_map = {
            'Terminal.EQ': '=',
            'EQ': '=',
            'Terminal.GT': '>',
            'GT': '>',
            'Terminal.LT': '<',
            'LT': '<',
            'Terminal.GTE': '>=',
            'GTE': '>=',
            'Terminal.LTE': '<=',
            'LTE': '<=',
            'Terminal.NEQ': '!=',
            'NEQ': '!='
        }

        # 先尝试直接映射
        if op in op_map:
            return op_map[op]

        # 如果是 Terminal.XXX 格式，提取后面部分再映射
        if op.startswith('Terminal.'):
            clean = op.split('.')[-1]
            return op_map.get(clean, clean)

        return op

    def plan_and_execute(self, table_manager, xid, quadruples):
        """
        解析四元式，生成'statement'对象，并调用TableManager执行。
        这是连接编译器和执行器的核心方法。

        Args:
            table_manager: TableManager的实例。
            xid: 当前的事务ID。
            quadruples: 编译器生成的四元式列表。

        Returns:
            TableManager返回的执行结果。
        """
        if not quadruples:
            raise ValueError("Cannot execute empty plan.")

        main_ops = {
            'CREATE_TABLE': self._translate_create,
            'INSERT_INTO': self._translate_insert,
            'SELECT_FROM': self._translate_select,
            'DELETE_FROM': self._translate_delete,
            'UPDATE': self._translate_update,
        }

        # 寻找核心操作四元式并调用对应的翻译方法
        for op, _, _, _ in quadruples:
            if op in main_ops:
                translator = main_ops[op]
                statement = translator(quadruples, table_manager)
                print("op:",op)
                print("statement:",statement)

                # 根据操作调用 TableManager 对应的方法
                if op == 'CREATE_TABLE':
                    return table_manager.create_table(xid, statement)
                elif op == 'INSERT_INTO':
                    return table_manager.insert(xid, statement)
                elif op == 'SELECT_FROM':
                    return table_manager.select(xid, statement)
                elif op == 'DELETE_FROM':
                    return table_manager.delete(xid, statement)
                elif op == 'UPDATE':
                    return table_manager.update(xid, statement)

        # 如果循环结束都没有找到任何一个核心操作
        first_op = quadruples[0][0]
        raise NotImplementedError(
            f"Execution for main operation '{first_op}' is not implemented, or no main operation found.")


    def _translate_create(self, quads,table_manager=None):
        main_quad = next((q for q in quads if q[0] == 'CREATE_TABLE'), None)
        if not main_quad:
            raise ValueError("Invalid quads for CREATE TABLE statement")

        table_name = main_quad[1]

        field_names = []
        field_types = []

        # 遍历所有四元式，找出 DEF_COLUMN 指令
        for op, arg1, arg2, res in quads:
            if op == 'DEF_COLUMN' and res == table_name:
                # arg1 是列名 (field_name), arg2 是列类型 (field_type)
                field_names.append(arg1)
                field_types.append(arg2)

        # 组装成 TableManager 期望的 statement 对象
        statement = SimpleNamespace(
            table_name=table_name,
            field_names=field_names,
            field_types=field_types,
            indexes=field_names
        )
        return statement

    def _translate_insert(self, quads,table_manager):
        main_quad = next((q for q in quads if q[0] == 'INSERT_INTO'), None)
        table_name = main_quad[1]

        values_dict = {}
        for op, arg1, arg2, res in quads:
            if op == 'VALUE_FOR_COL':
                values_dict[arg2] = arg1

        # *** 核心修复：根据表的真实列顺序来排序值 ***
        try:
            # 从 table_manager 获取表的 schema
            schema_info = table_manager.get_table_schema(table_name)
            # schema_info 是 [(col_name, col_type), ...]
            ordered_col_names = [col[0] for col in schema_info]
        except Exception as e:
            raise Exception(f"无法为表 '{table_name}' 获取列顺序：{e}")

        # 检查插入的列是否都存在
        if not set(values_dict.keys()).issubset(set(ordered_col_names)):
            raise ValueError("插入的值包含了表中不存在的列")

        # 按正确的列顺序构建 values 列表
        values = [values_dict.get(col_name) for col_name in ordered_col_names if col_name in values_dict]

        # 如果是部分列插入，需要用None或其他默认值填充
        if len(values) != len(ordered_col_names):
            # 这是一个简化的处理，实际数据库需要处理默认值
            # 这里我们假设所有列都被提供了值
            if len(values_dict) != len(ordered_col_names):
                raise ValueError(f"插入的值数量与表的列数不匹配。期望 {len(ordered_col_names)}，得到 {len(values_dict)}")
            values = [values_dict[col_name] for col_name in ordered_col_names]

        statement = SimpleNamespace(
            table_name=table_name,
            values=values
        )
        return statement


    def _translate_select(self, quads, table_manager):
            main_quad = next((q for q in quads if q[0] == 'SELECT_FROM'), None)
            if not main_quad:
                raise ValueError("Invalid quads for SELECT statement")

            table_name = main_quad[1]
            where_temp_var = main_quad[2]

            fields = [q[1] for q in quads if q[0] == 'TARGET']
            if not fields:
                fields = ['*']

            where_conditions = None
            if where_temp_var != '_':
                for op, arg1, arg2, res in quads:
                    if res == where_temp_var:
                        clean_op = self._clean_op(op)  # <--- 应用转换
                        where_conditions = {arg1: (clean_op, arg2)}
                        break

            statement = SimpleNamespace(
                table_name=table_name,
                fields=fields,
                where_conditions=where_conditions
            )
            print("statement:",statement)
            return statement


    def _translate_delete(self, quads, table_manager=None):
        main_quad = next((q for q in quads if q[0] == 'DELETE_FROM'), None)
        if not main_quad:
            raise ValueError("Invalid quads for DELETE statement")

        table_name = main_quad[1]
        where_temp_var = main_quad[2]

        where_conditions = None
        if where_temp_var != '_':
            for op, arg1, arg2, res in quads:
                if res == where_temp_var:
                    # *** 核心修复：调用 _clean_op 来转换操作符 ***
                    clean_op = self._clean_op(op)
                    where_conditions = {arg1: (clean_op, arg2)}
                    break

        statement = SimpleNamespace(
            table_name=table_name,
            where_conditions=where_conditions
        )
        print("statement:",statement)
        return statement

    def _translate_update(self, quads, table_manager=None):
        main_quad = next((q for q in quads if q[0] == 'UPDATE'), None)
        if not main_quad:
            raise ValueError("Invalid quads for UPDATE statement")

        table_name = main_quad[1]
        where_temp_var = main_quad[2]

        set_values = {}
        for op, arg1, arg2, res in quads:
            if op == 'SET':
                set_values[arg2] = arg1

        where_conditions = None
        if where_temp_var != '_':
            for op, arg1, arg2, res in quads:
                if res == where_temp_var:
                    # *** 核心修复：调用 _clean_op 来转换操作符 ***
                    clean_op = self._clean_op(op)
                    where_conditions = {arg1: (clean_op, arg2)}
                    break

        statement = SimpleNamespace(
            table_name=table_name,
            set_values=set_values,
            where_conditions=where_conditions
        )
        print("statement:",statement)
        return statement